﻿using MaterialDemo.IService.IPermission;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MaterialDemo.MVC.Filters
{
    public class MySqlPowerFilterAttribute: ActionFilterAttribute
    {
        #region 构造函数注入
        private readonly ILogger<MySqlPowerFilterAttribute> _logger;
        private readonly IModelMetadataProvider _modelMetadataProvider;
        private readonly IPowerService _powerService;

        public MySqlPowerFilterAttribute(ILogger<MySqlPowerFilterAttribute> logger
            , IModelMetadataProvider modelMetadataProvider,IPowerService powerService )//如果不传myRoleID进来，默认为0，表示只做session验证
        {
            _modelMetadataProvider = modelMetadataProvider;
            _logger = logger;
            _powerService = powerService;
        }
        #endregion


        /// <summary>
        /// 根据特性的角色id进行验证
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.Filters.Any(u => u is MyAllAllowAttribute))
            {
                return;//如果方法上有MyAllAllowAttribute特性。连session登录验证都不需要,直接通过验证
            }
            else
            {
                //如果有session过滤器独立出来，可以不在这里做session校验
                if (context.HttpContext.Session.GetString("UserId") == null)
                {
                    //调回登录页
                    context.Result = new RedirectResult("/Account/Login");
                }
                else
                {
                 
                    var allRoleId= context.HttpContext.Session.GetString("AllRoleId").ToString();
                    //拿到要访问的地址
                    string url = context.HttpContext.Request.Path;
                    //
                    if (_powerService.CheckPower(url,allRoleId))
                    {
                        return;//不做处理，表示验证通过
                    }
                    else
                    {
                        //记录日志
                        var controllerName = context.ActionDescriptor.RouteValues["controller"];
                        var actionName = context.ActionDescriptor.RouteValues["action"];
                        var userId = context.HttpContext.Session.GetString("UserId");
                        _logger.LogWarning($"{userId}试图进入{controllerName}控制器中的{actionName}被拒绝！");
                        //调回错误页面
                        var result = new ViewResult { ViewName = "~/Views/Shared/Error.cshtml" };
                        result.ViewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
                        result.ViewData.Add("Exception", "抱歉，你没有权限！");

                        context.Result = result;
                    }

                }
            }
        }


        private bool IsAjaxRequest(HttpRequest request)
        {
            string header = request.Headers["X-Requested-With"];
            return "XMLHttpRequest".Equals(header);
        }
    }
}
